/*
 * Copyright (C) 2010 TopCoder Inc., All Rights Reserved.
 */
package com.hercules.xre.protocol.testing.netty;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;

import com.hercules.xre.protocol.testing.Helper;
import com.topcoder.util.log.Log;
import com.topcoder.util.log.LogManager;

/**
 * <p>
 * Channel Listener Future that is responsible for logging errors that might occur when
 * performing I/O operations on channel.
 * </p>
 * <p>
 * <strong>Thread-safety:</strong> This class is immutable and thus it is thread safe.
 * </p>
 * @author TCSDESIGNER, TCSDEVELOPER
 * @version 1.0
*/
public class ExceptionHandlingChannelFutureListener implements ChannelFutureListener {
    /**
     * <p>
     * Logger that is used to log activities and errors.
     * </p>
     * <p>
     * It is initialized to LogManager.getLog(ExceptionHandlingChannelFutureListener.class.getName()).
     * Can not be null, never changes after initialization.
     * </p>
     */
    private static final Log LOGGER = LogManager.getLog(ExceptionHandlingChannelFutureListener.class.getName());

    /**
     * Empty default constructor.
     */
    public ExceptionHandlingChannelFutureListener() {
    }

    /**
     * <p>
     * Method called by Netty framework when channel operation has been completed.
     * If an exception was thrown during operation it should be caught and logged.
     * </p>
     *
     * @param future channel future representing message delivery event, can't be null
     * @throws IllegalArgumentException - when passed future is null
     */
    public void operationComplete(ChannelFuture future) {
        final String signature = "ExceptionHandlingChannelFutureListener#operationComplete";
        Helper.logEnter(signature, new String[] {"future"}, new Object[] {future}, LOGGER);
        try {
            Helper.checkNull(future, "future", signature, LOGGER);
            Throwable cause = future.getCause();
            if (cause != null) {
                // log the exception
                Helper.logError(cause, signature, LOGGER);
            }
        } finally {
            Helper.logExit(signature, null, LOGGER);
        }
    }
}

